/** * Sumpu Inc. * Copyright (c) 2011-2012 All Rights Reserved. */
package cn.sumpu.app.guoguojie.web.mvc.member;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.taobao.api.internal.util.codec.Base64;

import cn.sumpu.app.guoguojie.biz.AccountBiz;
import cn.sumpu.app.guoguojie.biz.AppconfBiz;
import cn.sumpu.app.guoguojie.biz.CmsContentBiz;
import cn.sumpu.app.guoguojie.biz.DoingTagShowBiz;
import cn.sumpu.app.guoguojie.biz.ImageBiz;
import cn.sumpu.app.guoguojie.biz.MailBiz;
import cn.sumpu.app.guoguojie.biz.MemberBiz;
import cn.sumpu.app.guoguojie.biz.MemberDetailBiz;
import cn.sumpu.app.guoguojie.biz.MessageBiz;
import cn.sumpu.app.guoguojie.biz.WeiboBiz;
import cn.sumpu.app.guoguojie.constant.OutAccountType;
import cn.sumpu.app.guoguojie.domain.Member;
import cn.sumpu.app.guoguojie.domain.MemberDetail;
import cn.sumpu.app.guoguojie.domain.MemberOutAccount;
import cn.sumpu.app.guoguojie.domain.OnLineUserListener;
import cn.sumpu.app.guoguojie.exception.AppBusinessException;
import cn.sumpu.app.guoguojie.util.Common;
import cn.sumpu.app.guoguojie.util.Constant;
import cn.sumpu.app.guoguojie.util.ImageWeb;
import cn.sumpu.app.guoguojie.util.PageModel;
import cn.sumpu.app.guoguojie.util.SecurityCode;
import cn.sumpu.toolkit.weibo.AccessUser;

/** *  * * @author grieous * @version $Id: MemberController.java, v 0.1 2012-8-7 上午11:57:06 grieous Exp $ */

@Controller
public class MemberController {
    private final static Logger logger = LoggerFactory.getLogger(MemberController.class);
    @Autowired
    private MemberBiz           memberBiz;
    @Autowired
    private MemberDetailBiz     memberDetailBiz;
    @Autowired
    private WeiboBiz            weiboBiz;
    @Autowired
    private ImageBiz            imageBiz;
    @Autowired
    private MailBiz             mailBiz;
    @Autowired
    private DoingTagShowBiz     tagBiz;
    @Autowired
    private CmsContentBiz       contentBiz;
    @Autowired
    private AccountBiz          accountBiz;
    @Autowired
    private MessageBiz          messageBiz;
    @Autowired
    private AppconfBiz          appconfBiz;

    //注册页面
    @RequestMapping(value = "/member/toreg.htm")
    public String toRegisterOutAccount(HttpServletRequest request) {
        request.setAttribute("requestType", "toRegisterOutAccount");
        return "v3/member/loginRegister/registerOutAccount";
    }

    @RequestMapping(value = "/member/toregister.htm")
    public String toRegister(HttpServletRequest request, MemberOutAccount memberOutAccount) {
        request.setAttribute("memberOutAccount", memberOutAccount);
        return "v3/member/loginRegister/register";
    }

    @RequestMapping(value = "/member/reg.htm")
    public String easyRegister(HttpServletRequest request, MemberOutAccount memberOutAccount) {
        request.setAttribute("memberOutAccount", memberOutAccount);
        request.setAttribute("requestType", "toRegisterOutAccount");
        return "v3/member/loginRegister/registerOutAccount";
    }

    //注册
    @RequestMapping(value = "/member/register.htm")
    public String register(MemberOutAccount memberOutAccount, Member member, HttpServletRequest request, HttpServletResponse response) {
        try {
            member.setRegisterIP(Common.getIp(request));
            member.setLoginIP(Common.getIp(request));
            List<MemberOutAccount> outAccountList = new ArrayList<MemberOutAccount>();
            outAccountList.add(memberOutAccount);
            member.setOutAccountList(outAccountList);
            member = memberBiz.register(member);
            if (!Common.empty(member) && !Common.empty(member.getIdentifier())) {
                String picUrl = request.getSession().getServletContext().getRealPath("/") + "/images/ad-weibo.jpg";
                memberBiz.sendRegWeibo(member, Constant.SEND_REGISTER_MESSAGE_WEIBO_CONTENT, picUrl);//发送注册微博
                accountBiz.createAccountByMemberId(member.getIdentifier());//注册果果帐号
                messageBiz.addClientFeedback(null, member.getNickname(), Constant.SEND_REGISTER_MESSAGE_CONTENT);//发送站内信
            }
            responseRedict(request, response, member, null);
        } catch (Exception e) {
            logger.error("[/member/register.htm] fail", e);
            e.printStackTrace();
        }
        return null;
    }

    //使用协议页面
    @RequestMapping(value = "/member/protocol.htm")
    public String protocol() {
        return "v3/member/loginRegister/protocol";
    }

    //登录页面
    @RequestMapping(value = "/member/tologin.htm")
    public String enterLogin(HttpServletRequest request, MemberOutAccount memberOutAccount) {
        String historyUrl = request.getHeader("Referer");
        request.setAttribute("historyUrl", historyUrl);
        request.setAttribute("memberOutAccount", memberOutAccount);
        return "v3/member/loginRegister/login";
    }

    //弹出登录页面
    @RequestMapping(value = "/member/poplogin.htm")
    public String popLogin(HttpServletRequest request, HttpServletResponse response) {
        Member member = OnLineUserListener.getSessionMember(request);
        if (Common.empty(member)) {
            String historyUrl = request.getHeader("Referer");
            request.setAttribute("historyUrl", historyUrl);
            return "v3/member/loginRegister/loginPop";
        }
        return null;
    }

    //登录
    @RequestMapping(value = "/member/login.htm")
    public String loginOperation(HttpServletRequest request, HttpServletResponse response, String loginType, String loginName, String loginPwd,
                                 String historyUrl) {
        try {
            Member member = memberBiz.login(loginName, loginPwd, Common.getIp(request));
            if (null == member) {
                PrintWriter out = response.getWriter();
                response.setContentType("text/html;charset=UTF-8");
                out.print("nologin");
            } else {
                request.setAttribute("historyUrl", historyUrl);
                responseRedict(request, response, member, null);
            }
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error("[/member/loginop.htm] fail", e);
            }
            e.printStackTrace();
        }
        return null;
    }

    //注册登录跳转
    private String responseRedict(HttpServletRequest request, HttpServletResponse response, Member member, AccessUser accessUser) throws IOException {
        String historyUrl = request.getParameter("historyUrl");
        if (Common.empty(member)) {
            request.setAttribute("accessUser", accessUser);
            request.setAttribute("historyUrl", historyUrl);
            if (Common.empty(accessUser)) {
                request.setAttribute("requestType", "toRegisterOutAccount");
            } else if (!Common.empty(accessUser.getUid()) && !Common.empty(accessUser.getDesc())) {
                request.setAttribute("requestType", "registerOutAccount");
            } else {
                request.setAttribute("requestType", "toRegisterOutAccount");
            }
            return "v3/member/loginRegister/registerOutAccount";
        }
        request.getSession(true).setAttribute("onlineUser", new OnLineUserListener(member));

        if (Common.empty(historyUrl) || historyUrl.equals("null")) {
            historyUrl = "/member/myshare.htm";
        } else {
            String reqUrl = historyUrl.substring(historyUrl.lastIndexOf("/") + 1);
            if (reqUrl.equals("tologin.htm") || reqUrl.equals("toregister.htm") || reqUrl.equals("toreg.htm") || Common.empty(reqUrl)) {
                historyUrl = "/member/myshare.htm";
            }
        }
        //普通登录
        if (Common.empty(accessUser)) {
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write(historyUrl);
        } else {
            //外部帐号登录
            response.sendRedirect(historyUrl);
        }
        return null;
    }

    //登录失败
    @RequestMapping(value = "/member/nologin.htm")
    public String noLogin(HttpServletRequest request) {
        String historyUrl = request.getHeader("Referer");
        request.setAttribute("historyUrl", historyUrl);
        request.setAttribute("error", "用户名或者密码不存在");
        return "v3/member/loginRegister/login";
    }

    //忘记密码页面
    @RequestMapping(value = "/member/tofindpwd.htm")
    public String toFindPwd(HttpServletRequest request, HttpServletResponse response) {
        Member member = OnLineUserListener.getSessionMember(request);
        if (!Common.empty(member)) {
            try {
                response.sendRedirect("/member/myshare.htm");
                return null;
            } catch (Exception e) {
                logger.error("[/member/tofindpwd.htm] fail", e);
            }
        }
        return "v3/member/loginRegister/findPassword";
    }

    @RequestMapping(value = "/member/findpwd.htm")
    public void findPassword(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setContentType("text/html;charset=UTF-8");
            String result = memberBiz.findPassword(request);
            response.getWriter().print(result);
        } catch (Exception e) {
            logger.error("[/member/findpwd.htm] fail", e);
            e.printStackTrace();
        }
    }

    //重置密码页面
    @RequestMapping(value = "/member/toresetpwd.htm")
    public String enterResetPwd(HttpServletRequest request, String number, String key, HttpServletResponse response) {
        try {
            if (Common.notEmptyStr(number) && Common.notEmptyStr(key)) {
                Member member = memberBiz.getLoginMemberById(number);
                String rpFlag = member.getResetPassword();
                // 验证数据正确性
                if (Common.notEmptyStr(rpFlag) && rpFlag.split("@").length == 3) {
                    String[] dbFlag = rpFlag.split("@");
                    String dbKey = dbFlag[0];
                    String isBoolean = dbFlag[1];
                    long date = Long.parseLong(dbFlag[2]);
                    long minutes = ((new Date()).getTime() - date) / (1000 * 60);
                    if (key.equals(dbKey) && "true".equals(isBoolean) && minutes < 10) {
                        request.setAttribute("memberId", member.getIdentifier());
                        member.setResetPassword("false");
                        memberBiz.updateMember(member);
                        return "v3/member/resetPassword";
                    }
                }
            }
            return "v3/member/loginRegister/resetPassword";
        } catch (Exception e) {
            logger.error("[/member/toresetpwd.htm] fail", e);
            e.printStackTrace();
            return null;
        }
    }

    // 重置密码
    @RequestMapping(value = "/member/resetpwd.htm")
    public String resetPassword(String memberId, String pwd, HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setContentType("text/html; charset=UTF-8");
            PrintWriter out = response.getWriter();
            if (Common.notEmptyStr(memberId) && Common.notEmptyStr(pwd)) {
                Member member = new Member();
                member.setIdentifier(memberId);
                member.setPassword(Common.md5(Common.md5(pwd)));
                memberBiz.updateMember(member);
                out.print("success");
            } else {
                return "v2/common/error";
            }
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error("[/member/resetpwd.htm] fail", e);
            }
        }
        return null;
    }

    //验证码图
    @RequestMapping(value = "/member/vertifimg.htm")
    public String registerIg(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("image/jpeg");
        response.setHeader("Cache-Control", "no-cache");
        try {
            ServletOutputStream output = response.getOutputStream();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            // 验证码类
            SecurityCode yanZhengMa = new SecurityCode();
            ImageIO.write(yanZhengMa.creatImageGB(), "jpeg", baos);
            output.write(baos.toByteArray());
            output.flush();
            // 储存验证码在session
            request.getSession().setAttribute("vertiCode", yanZhengMa.sgbRand);
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error("[/member/vertifimg.htm] fail", e);
            }
        }
        return null;
    }

    //退出
    @RequestMapping(value = "/member/logout.htm")
    public String logout(HttpServletRequest request, HttpServletResponse response) {
        try {
            Cookie cookie1 = new Cookie("guoguojie_user_loginName", null);
            Cookie cookie2 = new Cookie("guoguojie_user_loginPwd", null);
            cookie1.setMaxAge(0);
            cookie2.setMaxAge(0);
            response.addCookie(cookie1);
            response.addCookie(cookie2);
            HttpSession session = request.getSession(true);
            session.removeAttribute("onlineUser");
            session.removeAttribute("member");
            session.removeAttribute("superMan");
            response.sendRedirect("/");
            return null;
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error("[/member/logout.htm] fail", e);
            }
            return "v2/common/error";
        }
    }

    //新浪微博登录
    @RequestMapping(value = "/member/sinalogin.htm")
    public void sinaLogin(HttpServletResponse response, String historyUrl) {
        try {
            String rel = weiboBiz.requestOauthSina(historyUrl);
            response.sendRedirect(rel);
        } catch (Exception e) {
            logger.error("[/member/sinalogin.htm] fail", e);
            e.printStackTrace();
        }
    }

    //新浪微博登录回调处理
    @RequestMapping(value = "/member/sinacallback.htm")
    public String sinaCallBack(String oauth_verifier, HttpServletRequest request, HttpServletResponse response, String historyUrl) {
        try {
            AccessUser accessUser = memberBiz.oauth(oauth_verifier, OutAccountType.SINA_WEIBO.getValue());
            accessUser.setDesc(OutAccountType.SINA_WEIBO.getValue());
            Member member = memberBiz.outLogin(accessUser, request);
            request.setAttribute("historyUrl", historyUrl);
            return responseRedict(request, response, member, accessUser);
        } catch (Exception e) {
            logger.error("[/member/sinacallback.htm] fail", e);
            e.printStackTrace();
        }

        return null;
    }

    //腾讯微博登录
    @RequestMapping(value = "/member/tencentlogin.htm")
    public void tencentLogin(HttpServletResponse response, String historyUrl) {
        try {
            response.sendRedirect(weiboBiz.requestOauthTencent(historyUrl));
        } catch (Exception e) {
            logger.error("[/member/tencentlogin.htm] fali", e);
            e.printStackTrace();
        }
    }

    //腾讯微博登录回调处理
    @RequestMapping(value = "/member/tencentcallback.htm")
    public String tencentCallBack(String oauth_verifier, HttpServletRequest request, HttpServletResponse response, String historyUrl) {
        try {
            AccessUser accessUser = memberBiz.oauth(oauth_verifier, OutAccountType.TENCENT_WEIBO.getValue());
            accessUser.setDesc(OutAccountType.TENCENT_WEIBO.getValue());
            String headUrl = accessUser.getHeadUrl();
            if (!Common.empty(headUrl)) {
                headUrl = headUrl.substring(0, headUrl.lastIndexOf("/") + 1) + "100";
            }
            accessUser.setHeadUrl(headUrl);
            Member member = memberBiz.outLogin(accessUser, request);
            request.setAttribute("historyUrl", historyUrl);
            return responseRedict(request, response, member, accessUser);
        } catch (Exception e) {
            logger.error("[/member/tencentcallback.htm] fali", e);
            e.printStackTrace();
        }
        return null;
    }

    // QQ登录
    @RequestMapping(value = "/member/qqlogin.htm")
    public String qqLogin(HttpServletResponse response, String historyUrl) {
        try {
            String url = memberBiz.qqLogin(historyUrl);
            response.sendRedirect(url);
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error("[/member/qqlogin.htm] fail", e);
            }
        }
        return null;
    }

    @RequestMapping(value = "/qqloginback.htm")
    public String qqLoginCallback(HttpServletResponse response, HttpServletRequest request) {
        try {
            String code = request.getParameter("code");
            String state = request.getParameter("state");
            AccessUser accessUser = memberBiz.qqLoginCallback(code, state);
            Member member = memberBiz.outLogin(accessUser, request);
            request.setAttribute("historyUrl", state);
            return responseRedict(request, response, member, accessUser);
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error("[/member/qqloginback.htm] fail", e);
            }
        }
        return null;
    }

    // 淘宝登录
    @RequestMapping(value = "/member/toplogin.htm")
    public String taobaoLogin(HttpServletResponse response, String historyUrl) throws AppBusinessException {
        try {
            response
                .sendRedirect("https://oauth.taobao.com/authorize?response_type=user&client_id=21080975&redirect_uri=http://www.guoguojie.com/top.htm?historyUrl="
                              + historyUrl);
        } catch (IOException e) {
            logger.error("[/member/toplogin.htm] fali", e);
            e.printStackTrace();
        }
        return null;
    }

    // 淘宝开放平台回调地址
    @RequestMapping(value = "/top.htm")
    public String top(HttpServletRequest request, HttpServletResponse response, String historyUrl) {
        try {
            String top_parameters = request.getParameter("top_parameters");
            String encode = request.getParameter("encode");
            Map<String, String> map = convertBase64StringtoMap(top_parameters, encode);
            String visitor_id = map.get("user_id");
            String visitor_nick = map.get("nick");
            String top_session = request.getParameter("top_session");//FIXME 临时解决方案
            if (null != top_session) {//FIXME 临时解决方案
                appconfBiz.setTopSession(top_session);//FIXME 临时解决方案
                response.sendRedirect("http://www.guoguojie.com/misc/main.htm");//FIXME 临时解决方案
                return null;//FIXME 临时解决方案
            }//FIXME 临时解决方案
            AccessUser accessUser = new AccessUser();
            accessUser.setUid(visitor_id);
            accessUser.setName(visitor_nick);
            accessUser.setDesc(OutAccountType.TAOBAO.getValue());
            Member member = memberBiz.outLogin(accessUser, request);
            request.setAttribute("historyUrl", historyUrl);
            return responseRedict(request, response, member, accessUser);
        } catch (Exception e) {
            logger.error("[top.htm] fail", e);
        }

        return null;
    }

    //基本信息修改页面
    @RequestMapping(value = "/member/personal.htm")
    public String personal(HttpServletRequest request) {
        Member member = OnLineUserListener.getSessionMember(request);
        if (Common.empty(member)) {
            return "v3/member/loginRegister/login";
        }
        request.setAttribute("member", member);
        return "v3/member/settings/personal";
    }

    //激活邮箱页面
    @RequestMapping(value = "/member/toactivemail.htm")
    public String toActiveMail(HttpServletRequest request) {
        Member member = OnLineUserListener.getSessionMember(request);
        if (Common.empty(member)) {
            return "v3/member/loginRegister/login";
        }
        if (member.getIsActive()) {
            return "v3/member/member";
        }
        request.setAttribute("member", member);
        return "v3/member/settings/activeEmail";
    }

    //激活邮箱
    @RequestMapping(value = "/member/active.htm")
    public String activeEmail(HttpServletRequest request, HttpServletResponse response) {
        Member member = OnLineUserListener.getSessionMember(request);
        if (Common.empty(member)) {
            return "v3/member/loginRegister/login";
        }
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter pw = null;
        try {
            String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/";
            mailBiz.sendEmail(basePath, member, null, null);
            pw = response.getWriter();
            pw.print("success");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("[/member/active.htm] fail", e);
        }
        return null;
    }

    @RequestMapping(value = "/member/activemail.htm")
    public String activeMail(HttpServletRequest request, HttpServletResponse response, String email) {
        Member member = OnLineUserListener.getSessionMember(request);
        if (Common.empty(member)) {
            return "v3/member/loginRegister/login";
        }
        if (!Common.empty(email)) {
            member.setEmail(email);
            try {
                memberBiz.updateMember(member);
                response.getWriter().write("success");
            } catch (Exception e) {
                logger.error("[/member/activemail.htm] fail", e);
                e.printStackTrace();
            }
        }

        return null;
    }

    //邮箱验证回来的请求
    @RequestMapping(value = "/member/emailvalidate.htm")
    public String successValede(String number, String activeCode, HttpServletRequest request, HttpServletResponse response) throws AppBusinessException {
        try {
            Member member = memberBiz.activeMember(number, activeCode);
            if (member == null) {
                return "v3/member/loginRegister/login";
            } else {
                member = memberBiz.loginCallback(member);
                request.getSession(true).setAttribute("onlineUser", new OnLineUserListener(member));
                return "v3/member/settings/emailValidate";
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("[/member/emailvalidate.htm] fail", e);
            return "v2/common/error";
        }
    }

    //保存基本信息
    @RequestMapping(value = "/member/savepersonal.htm")
    public String savePersonal(HttpServletRequest request, HttpServletResponse response, MemberDetail detail, String year, String month, String day) {
        Member member = OnLineUserListener.getSessionMember(request);
        if (Common.empty(member)) {
            return "v3/member/loginRegister/login";
        }
        try {
            response.setContentType("text/html; charset=UTF-8");
            PrintWriter pw = null;
            pw = response.getWriter();
            detail.setMember(member.getIdentifier());
            String birthday = null;
            if (!Common.empty(year) && !Common.empty(month)) {
                birthday = year + "-" + month;
            }
            if (!Common.empty(day)) {
                birthday += "-" + day;
            }
            detail.setBirthday(birthday);
            memberDetailBiz.saveMemberDetail(detail);
            member.setMemberDetail(detail);
            pw.print("success");
        } catch (Exception e) {
            logger.error("[/member/savepersonal.htm] fail", e);
            e.printStackTrace();
        }
        return null;
    }

    //头像修改页面
    @RequestMapping(value = "/member/avatar.htm")
    public String avatar(HttpServletRequest request) {
        Member member = OnLineUserListener.getSessionMember(request);
        if (Common.empty(member)) {
            return "v3/member/loginRegister/login";
        }
        request.setAttribute("member", member);
        return "v3/member/settings/avatar";
    }

    //上传头像
    @RequestMapping(value = "/member/avatarup.htm")
    public String avatarUpload(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter pw = null;
        try {
            Member member = OnLineUserListener.getSessionMember(request);
            request.setAttribute("fileType", "avatar");
            request.setAttribute("fileName", member.getIdentifier());
            ImageWeb imageWeb = imageBiz.uploadOneImg(request);
            pw = response.getWriter();
            pw.println(JSONObject.fromObject(imageWeb).toString());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("[/member/avatarup.htm] fail", e);
        }
        return null;
    }

    //确认修改头像
    @RequestMapping(value = "/member/avatarcut.htm")
    public String avatarCut(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setContentType("text/html; charset=UTF-8");
            PrintWriter pw = null;
            pw = response.getWriter();
            String srcImg = request.getParameter("srcImg");
            if (!Common.empty(srcImg)) {
                int x = Integer.parseInt(request.getParameter("x"));
                int y = Integer.parseInt(request.getParameter("y"));
                int w = Integer.parseInt(request.getParameter("w"));
                int h = Integer.parseInt(request.getParameter("h"));
                int realWidth = Integer.parseInt(request.getParameter("realWidth"));
                int realHeight = Integer.parseInt(request.getParameter("realHeight"));
                request.setAttribute("fileType", "avatar");
                memberBiz.cutAvatar(request, srcImg, x, y, w, h, realWidth, realHeight);
                pw.print("success");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("[/member/avatarcut.htm] fail", e);
        }
        return null;
    }

    //密码修改页面
    @RequestMapping(value = "/member/tosetpwd.htm")
    public String resetpwd(HttpServletRequest request) {
        Member member = OnLineUserListener.getSessionMember(request);
        if (Common.empty(member)) {
            return "v3/member/loginRegister/login";
        }
        request.setAttribute("member", member);
        return "v3/member/settings/setPwd";
    }

    // 修改密码
    @RequestMapping(value = "/member/setpwd.htm")
    public String setPwd(String oldpwd, String newpwd, String newpwdagain, HttpServletRequest request, HttpServletResponse response) {
        Member member = OnLineUserListener.getSessionMember(request);
        if (Common.empty(member)) {
            return "v3/member/loginRegister/login";
        }
        try {
            response.setContentType("text/html; charset=UTF-8");
            PrintWriter out = response.getWriter();
            if (!Common.empty(oldpwd)) {
                oldpwd = Common.md5(Common.md5(oldpwd));
                if (oldpwd.equals(member.getPassword())) {
                    member.setPassword(Common.md5(Common.md5(newpwd)));
                    memberBiz.updateMember(member);
                    out.print("success");
                } else {
                    out.print("error");
                }
            } else {
                if (Common.empty(member.getPassword())) {
                    member.setPassword(Common.md5(Common.md5(newpwd)));
                    memberBiz.updateMember(member);
                    out.print("success");
                }

            }
            request.setAttribute("member", member);
        } catch (Exception e) {
            logger.error("[/member/setpwd.htm] fail", e);
            e.printStackTrace();
        }

        return null;
    }

    // 我的关注
    @RequestMapping(value = "/member/follow.htm")
    public String meFollow(HttpServletRequest request, Integer page) {
        Member member = OnLineUserListener.getSessionMember(request);
        if (Common.empty(member)) {
            return "v3/member/loginRegister/login";
        }
        try {
            PageModel pageModel = memberBiz.getMemberFollows(member.getIdentifier(), page, null);
            request.setAttribute("pageModel", pageModel);
            member = memberBiz.getLoginMemberById(member.getIdentifier());
        } catch (AppBusinessException e) {
            logger.error("[/member/follow.htm] fail", e);
        }
        request.setAttribute("member", member);
        return "v3/member/fans/meFollow";
    }

    // 我的粉丝
    @RequestMapping(value = "/member/fans.htm")
    public String meFans(HttpServletRequest request, Integer page) {
        Member member = OnLineUserListener.getSessionMember(request);
        if (Common.empty(member)) {
            return "v3/member/loginRegister/login";
        }
        try {
            PageModel pageModel = memberBiz.getMemberFans(member.getIdentifier(), page, null);
            request.setAttribute("pageModel", pageModel);
            member = memberBiz.getLoginMemberById(member.getIdentifier());
        } catch (AppBusinessException e) {
            logger.error("[/member/fans.htm] fail", e);
        }
        request.setAttribute("member", member);
        return "v3/member/fans/meFans";
    }

    // 添加关注
    @RequestMapping(value = "/member/addfans.htm")
    public String addfans(String follow, Integer each, HttpServletRequest request, HttpServletResponse response) {
        Member member = OnLineUserListener.getSessionMember(request);
        if (!Common.empty(member)) {
            try {
                response.setContentType("text/html; charset=UTF-8");
                PrintWriter out = response.getWriter();
                String result = memberBiz.addFans(member.getIdentifier(), follow, each);
                out.print(result);
            } catch (Exception e) {
                logger.error("[/member/addfans.htm] fail", e);
                e.printStackTrace();
            }
        }
        return null;
    }

    // 取消关注
    @RequestMapping(value = "/member/cancelfans.htm")
    public String cancelfans(String follow, HttpServletRequest request, HttpServletResponse response) {
        Member member = OnLineUserListener.getSessionMember(request);
        if (!Common.empty(member)) {
            try {
                response.setContentType("text/html; charset=UTF-8");
                PrintWriter out = response.getWriter();
                memberBiz.cancelFans(member.getIdentifier(), follow);
                out.print("success");
            } catch (Exception e) {
                logger.error("[/member/cancelfans.htm] fail", e);
                e.printStackTrace();
            }
        }
        return null;
    }

    // 邮箱验证
    @RequestMapping(value = "/member/checkemail.htm")
    public void checkEmail(HttpServletRequest request, HttpServletResponse response) {
        String email = request.getParameter("email");
        if (Common.empty(email))
            return;
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter pw = null;
        try {
            pw = response.getWriter();
            Member m = memberBiz.getMemberEmail(email);
            if (m != null) {
                pw.print(false);
            } else {
                pw.print(true);
            }
        } catch (Exception e) {
            logger.error("[/member/checkemail.htm] fail", e);
            e.printStackTrace();
        }
    }

    // 昵称验证
    @RequestMapping(value = "/member/checknickname.htm")
    public void ckNickname(HttpServletRequest request, HttpServletResponse response, String nickname) {
        if (Common.empty(nickname))
            return;
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter pw = null;
        try {
            pw = response.getWriter();
            Member m = memberBiz.getMemberByNickname(nickname);
            if (Common.empty(m)) {
                pw.print(true);
            } else {
                pw.print(false);
            }
        } catch (Exception e) {
            logger.error("[/member/checknickname.htm] fail", e);
            e.printStackTrace();
        }
    }

    //检查是否登录
    @RequestMapping(value = "/member/checklogin.htm")
    public String checkMemberLogin(HttpServletRequest request, HttpServletResponse response) {
        Member member = OnLineUserListener.getSessionMember(request);
        try {
            PrintWriter out = response.getWriter();
            response.setContentType("text/html;charset=UTF-8");
            if (!Common.empty(member)) {
                out.print("logged");
            } else {
                out.print("nologin");
            }
        } catch (Exception e) {
            logger.error("[/member/checklogin.htm] fail");
            e.printStackTrace();
        }
        return null;
    }

    //设置cookie
    @SuppressWarnings("unused")
    private void setLoginCookie(HttpServletRequest request, HttpServletResponse response) {
        String autoLogin = request.getParameter("autoLogin");
        if (Common.notEmptyStr(autoLogin)) {
            String loginName = request.getParameter("loginName");
            String loginPwd = request.getParameter("loginPwd");
            try {
                Cookie cookieLoginName = new Cookie("guoguojie_user_loginName", URLEncoder.encode(loginName, "utf-8"));
                Cookie cookieLoginPwd = new Cookie("guoguojie_user_loginPwd", URLEncoder.encode(loginPwd, "utf-8"));
                cookieLoginName.setMaxAge(60 * 60 * 24 * 30); // 一个月有效
                cookieLoginPwd.setMaxAge(60 * 60 * 24 * 30); // 一个月有效
                response.addCookie(cookieLoginName);
                response.addCookie(cookieLoginPwd);
            } catch (Exception e) {
                logger.error("[setLoginCookie] fail", e);
                e.printStackTrace();
            }

        }
    }

    // 把TOP经过BASE64编码的字符串转换为Map对象
    private static Map<String, String> convertBase64StringtoMap(String str, String encode) {
        Map<String, String> map = new HashMap<String, String>();
        if (null == str) {
            return map;
        }
        if (null == encode) {
            encode = "UTF-8";
        }
        String keyvalues = null;
        try {
            keyvalues = new String(Base64.decodeBase64(URLDecoder.decode(str, "UTF-8").getBytes(encode)), encode);
        } catch (UnsupportedEncodingException e) {
            logger.warn("Parse TOP parameters fail", e);
        }
        if (keyvalues != null) {
            String[] keyvalueArray = keyvalues.split("\\&");
            for (String keyvalue : keyvalueArray) {
                String[] s = keyvalue.split("\\=");
                if (s == null || s.length != 2) {
                    return null;
                }
                map.put(s[0], s[1]);
            }
        }
        return map;
    }

    @RequestMapping(value = "/getsonid.htm")
    public String superFiend(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            PrintWriter out = response.getWriter();
            response.setContentType("text/html;charset=UTF-8");
            Map<String, Object> map = new HashMap<String, Object>();
            List<Member> superSonList = memberBiz.getSuperSonList(map);
            Random no = new Random();
            int son = no.nextInt(superSonList.size());
            String memberId = superSonList.get(son).getIdentifier();
            out.print(memberId);
        } catch (AppBusinessException e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping(value = "/member/getuserinfo.htm")
    public String getLoginMember(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html; charset=UTF-8");
        try {
            PrintWriter out = response.getWriter();
            Member member = OnLineUserListener.getSessionMember(request);
            out.println(JSONObject.fromObject(member));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("[/member/avatarup.htm] fail", e);
        }
        return null;
    }

    /**
     * author BruceZhang
     * @param request
     * @param response
     * @param page
     * @return  我的分享
     * @throws IOException
     */
    @RequestMapping(value = "/member/myshare.htm")
    public String myshare(HttpServletRequest request, HttpServletResponse response, Integer page) {
        try {
            Member member = OnLineUserListener.getSessionMember(request);
            if (Common.empty(member)) {
                return "v3/member/loginRegister/login";
            }
            PageModel pageModel = tagBiz.getDoingByMember(member.getIdentifier(), page);
            request.setAttribute("pageModel", pageModel);
            request.setAttribute("member", memberBiz.getLoginMemberById(member.getIdentifier()));
            //底部
            contentBiz.pushContent(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "v3/member/myshare";
    }

    /**
     * author BruceZhang
     * @param request
     * @param response
     * @param page
     * @return  我的收藏
     * @throws IOException
     */
    @RequestMapping(value = "/member/mylove.htm")
    public String mylove(HttpServletRequest request, HttpServletResponse response, Integer page) {
        try {
            Member member = OnLineUserListener.getSessionMember(request);
            if (Common.empty(member)) {
                return "v3/member/loginRegister/login";
            }
            PageModel pageModel = tagBiz.getDlByMember(member.getIdentifier(), page);
            request.setAttribute("pageModel", pageModel);
            request.setAttribute("member", memberBiz.getLoginMemberById(member.getIdentifier()));
            //底部
            contentBiz.pushContent(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "v3/member/mylove";
    }

    /**
     * author Grieous
     * @param request
     * @param response
     * @param page
     * @return  TA的分享
     * @throws IOException
     */
    @RequestMapping(value = "/member/tashare.htm")
    public String taShare(HttpServletRequest request, HttpServletResponse response, Integer page, String ta) {
        try {
            Member member = memberBiz.getLoginMemberById(ta);
            if (!Common.empty(member)) {
                Member myMember = OnLineUserListener.getSessionMember(request);
                if (!Common.empty(myMember)) {
                    if (myMember.getIdentifier().equals(ta)) {
                        response.sendRedirect("/member/myshare.htm");
                        return null;
                    }
                    int follow = memberBiz.checkFollow(myMember.getIdentifier(), ta);
                    request.setAttribute("follow", follow);
                }
                PageModel pageModel = tagBiz.getDoingByMember(member.getIdentifier(), page);
                request.setAttribute("pageModel", pageModel);
                request.setAttribute("member", member);
            }

        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error("[/member/tashare.htm] fail", e);
            }
        }
        return "v3/member/taHome/tashare";
    }

    /**
     * author Grieous
     * @param request
     * @param response
     * @param page
     * @return  TA的收藏
     * @throws IOException
     */
    @RequestMapping(value = "/member/talove.htm")
    public String talove(HttpServletRequest request, HttpServletResponse response, Integer page, String ta) {
        try {
            Member member = memberBiz.getLoginMemberById(ta);
            if (!Common.empty(member)) {
                Member myMember = OnLineUserListener.getSessionMember(request);
                if (!Common.empty(myMember)) {
                    if (myMember.getIdentifier().equals(ta)) {
                        response.sendRedirect("/member/mylove.htm");
                        return null;
                    }
                    int follow = memberBiz.checkFollow(myMember.getIdentifier(), ta);
                    request.setAttribute("follow", follow);
                }
                PageModel pageModel = tagBiz.getDlByMember(member.getIdentifier(), page);
                request.setAttribute("pageModel", pageModel);
                request.setAttribute("member", member);
            }

        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error("[/member/talove.htm] fail", e);
            }
        }
        return "v3/member/taHome/talove";
    }

    // TA的关注
    @RequestMapping(value = "/member/tafollow.htm")
    public String taFollow(HttpServletRequest request, Integer page, String ta) {
        try {
            Member member = memberBiz.getLoginMemberById(ta);
            if (!Common.empty(member)) {
                Member myMember = OnLineUserListener.getSessionMember(request);
                String me = null;
                if (!Common.empty(myMember)) {
                    int follow = memberBiz.checkFollow(myMember.getIdentifier(), ta);
                    request.setAttribute("follow", follow);
                    me = myMember.getIdentifier();
                }
                PageModel pageModel = memberBiz.getMemberFollows(member.getIdentifier(), page, me);
                request.setAttribute("pageModel", pageModel);
                request.setAttribute("member", member);

            }
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error("[/member/tafollow.htm] fail", e);
            }
        }

        return "v3/member/taHome/taFollow";
    }

    // TA的粉丝
    @RequestMapping(value = "/member/tafans.htm")
    public String taFans(HttpServletRequest request, Integer page, String ta) {
        try {
            Member member = memberBiz.getLoginMemberById(ta);
            if (!Common.empty(member)) {
                Member myMember = OnLineUserListener.getSessionMember(request);
                String me = null;
                if (!Common.empty(myMember)) {
                    int follow = memberBiz.checkFollow(myMember.getIdentifier(), ta);
                    request.setAttribute("follow", follow);
                    me = myMember.getIdentifier();
                }
                PageModel pageModel = memberBiz.getMemberFans(member.getIdentifier(), page, me);
                request.setAttribute("pageModel", pageModel);
                request.setAttribute("member", member);

            }
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error("[/member/tafans.htm] fail", e);
            }
        }

        return "v3/member/taHome/taFans";
    }
}
